package eu.liquify.ui {
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	public class Utils {
		
		/**
		 * 
		 * @param	txt
		 * @param	text
		 * @param	width
		 * @param	ellipsisFormat
		 * @param	ellipsisWidth
		 * @return true if the text was truncated
		 */
		public static function resizeTextField(txt:TextField, text:String, width:Number, ellipsisFormat:TextFormat = null, ellipsisWidth:Number = 13):Boolean {
			txt.text = text;
			txt.autoSize = TextFieldAutoSize.LEFT;
			var txtWidth:Number = txt.width;
			var txtHeight:Number = txt.height;
			var trunc:Boolean = false;
			if (width < txtWidth) {
				txtWidth = width;
				var index:int = txt.getCharIndexAtPoint(width, txtHeight/2);
				if (index > -1) {
					var spaceLeft:Number = 0;
					for (; index >= 0; index--) {
						var charBounds:Rectangle = txt.getCharBoundaries(index);
						spaceLeft = width-charBounds.left;
						if (spaceLeft > ellipsisWidth) break;
					}
					if (index > 0) {
						txt.text = text.substr(0, Math.max(0, index))+"...";
						if (ellipsisFormat) txt.setTextFormat(ellipsisFormat, txt.length-3, txt.length);
						txtWidth = txt.width;
						trunc = true;
					}
				}
			}
			txt.autoSize = TextFieldAutoSize.NONE;
			txt.width = Math.max(0, txtWidth+2); // +2 -> Cut off char bug fix
			txt.height = txtHeight;
			return trunc;
		}
		
		/**
		 * Calls the function f with an arbitrary number of arguments and omits extra ones the function doesn't accept
		 * @param	f
		 * @param	...args
		 * @return
		 */
		public static function callDynamic(f:Function, ...args:Array):* {
			if (args.length < f.length) throw new ArgumentError("Dynamic call error: Argument count shortage on "+f+". Expected "+f.length+", got "+args.length+".");
			args.splice(f.length, args.length-f.length);
			return f.apply(null, args);
		}
		
		public static function pad(text:String, padding:String, length:uint):String {
			while (text.length+padding.length <= length) {
				text = padding+text;
			}
			return text;
		}
		
	}

}